<?php

namespace app\apiv1\controller;

use app\store\service\GoodsService;
use service\DataService;
use service\ToolsService;
use service\WechatService;
use controller\BasicIndex;
use think\Db;
use think\Validate;

require_once(ROOT_PATH . '/vendor/eth/eth/eth.class.php');

class Common extends Base
{
    public $page;
    public $max_page_num;

    public function __construct()
    {
        parent::__construct();

        $page = input('param.page');
        $max_page_num = input('param.max_page_num');
        $this->page = isset($page) ? $page : 1;
        $this->max_page_num = isset($max_page_num) ? $max_page_num : 10;
    }


    public function getSysParams()
    {
        $list = Db::table('system_config')->select();
        $array = [];
        foreach ($list as $v) {
            $array[$v['name']] = $v['value'];
        }
        $this->success('', $array);
    }


    public function getJSSDK()
    {
        $this->success('', WechatService::webJsSDK('http://humei.fhtest.vip/system/#/union'));
    }

    public
    function fileImage()
    {

        $image = request()->post('image');
        if ($image) {
            $res = $this->saveBase64Image($image);
            return $this->success($res);
        } else {
            return $this->error('上传失败');
        }
    }

    function saveBase64Image($base64_image_content)
    {

        if (preg_match('/^(data:\s*image\/(\w+);base64,)/', $base64_image_content, $result)) {

            //图片后缀
            $type = $result[2];
            if ($type == 'jpeg')
                $type = 'jpg';

            $ext = strtolower(sysconf('storage_local_exts'));

            if (is_string($ext)) {
                $ext = explode(',', $ext);
            }

            if (!in_array($type, $ext)) {
                $data['code'] = 0;
                $data['imgageName'] = '';
                $data['image_url'] = '';
                $data['type'] = '';
                $data['msg'] = '不允许上传的文件类型';
                return $data;
            }

            //保存位置--图片名
            $image_name = date('His') . str_pad(mt_rand(1, 99999), 5, '0', STR_PAD_LEFT) . "." . $type;
            $iamge_dir = 'upload/' . date('Ymd');
            $image_url = $iamge_dir . $image_name;
            if (!is_dir(dirname('./' . $iamge_dir))) {
                mkdir(dirname('./' . $iamge_dir));
                chmod(dirname('./' . $iamge_dir), 0777);
            }

            //解码
            $decode = base64_decode(str_replace($result[1], '', $base64_image_content));
            if (file_put_contents('./' . $image_url, $decode)) {
                $appRoot = request()->root();  // 去掉参数 true 将获得相对地址
                $uriRoot = preg_match('/\.php$/', $appRoot) ? dirname($appRoot) : $appRoot;
                $uriRoot = in_array($uriRoot, ['/', '\\']) ? '' : $uriRoot;

                $data['code'] = 1;
                $data['imageName'] = $image_name;
                $data['image_url'] = $uriRoot . '/' . $image_url;
                $data['type'] = $type;
                $data['msg'] = '保存成功！';
            } else {
                $data['code'] = 0;
                $data['imgageName'] = '';
                $data['image_url'] = '';
                $data['type'] = '';
                $data['msg'] = '图片保存失败！';
            }
        } else {
            $data['code'] = 0;
            $data['imgageName'] = '';
            $data['image_url'] = '';
            $data['type'] = '';
            $data['msg'] = 'base64图片格式有误！';
        }
        return $data;
    }

    public
    function banner()
    {
        $list = Db::name('es_article')->where(['type' => 'business', 'status' => 1])->select();
        $this->success($list);
    }


    public
    function goodsList()
    {
        $get = $this->request->get();
        $db = Db::name('StoreGoods')->where(['is_deleted' => '0']);
        if (isset($get['tags_id']) && $get['tags_id'] !== '') {
            $db->whereLike('tags_id', "%,{$get['tags_id']},%");
        }
        if (isset($get['goods_title']) && $get['goods_title'] !== '') {
            $db->whereLike('goods_title', "%{$get['goods_title']}%");
        }
        foreach (['cate_id', 'brand_id'] as $field) {
            (isset($get[$field]) && $get[$field] !== '') && $db->where($field, $get[$field]);
        }
        if (isset($get['create_at']) && $get['create_at'] !== '') {
            list($start, $end) = explode(' - ', $get['create_at']);
            $db->whereBetween('create_at', ["{$start} 00:00:00", "{$end} 23:59:59"]);
        }
        $data = $db->order('status desc,sort asc,id desc')->page($this->page, $this->max_page_num)->select();
        $result = GoodsService::buildGoodsList($data);
        $this->success('', [
            'goods_list' => $result['list'],
            'brands' => $result['brand'],
            'cates' => ToolsService::arr2table($result['cate']),
        ]);
    }

    //获取商品详细
    public
    function getGoodsDetail()
    {
        $goods_id = $this->request->param('id');
        $goodsList = Db::name('StoreGoods a')
            ->field('a.goods_image,a.goods_title,a.goods_content,b.goods_number,b.selling_price,b.goods_spec')
            ->join('store_goods_list b', "a.id = b.goods_id")
            ->where(['a.id' => $goods_id, 'a.is_deleted' => 0])
            ->find();
        empty($goodsList) && $this->error('商品不存在!');

        $goodsList['goods_image'] = explode('|', $goodsList['goods_image']);

        $this->success('', $goodsList);
    }


    public function getMeritList()
    {
    	
     $user = Db::name('store_member')->where('id',$this->wx_user_id)->find();
//     dump($user['shop_id']);
        $data = Db::name('sys_lettery')->where('shop_id',$user['shop_id'])->field('id,sort,title')->order('sort adc')->select();
        $this->success('', $data);
    }

    public
    function getByIdMeritDetail()
    {
        $data = input('post.');
        $validate = Validate::make([
            'id' => 'require',
        ], [
            'id.require' => '功勋id缺少！',

        ]);
        $validate->check($data) || $this->error($validate->getError());
        $data = Db::name('sys_lettery')->field('content,title')->where('sort', $data['id'])->order('sort adc')->select();
        $this->success('', $data);
    }


    public
    function sendMobileMessage()
    {
        $code = rand(10000, 99999);
        $data = input('param.');
        if (empty($data['phone'])) {
            $data['phone'] = Db::name('store_member')->where(['id' => $this->wx_user_id])->value('phone');
            !$data['phone'] && $this->error('账号不存在');
            $this->setSmsCode('code', $code, $data['phone']);
            $result = sendMobileMessage($data['phone'], ['code' => $code], '499532');
            $this->success($result);
        }
    }


    public
    function getShopsList()
    {
        header('content-type:application:json,charset=utf-8');
        header('Access-Control-Allow-Origin,*');
        header('Access-Control-Methods:GET,POST,OPTIONS');
        header('Access-Control-Allow-Headers:origin,x-requested-with,with,content-type');
        header('Access-Control-Max-Age:3600');
        header('X-Frame-Options:deny');

        $data = input('param.');
        $validate = Validate::make([
            'lng' => 'require',
            'lat' => 'require',
        ], [
          //  'lng.require' => '缺少经度！',
           // 'lat.require' => '缺少纬度！',

        ]);
       if(empty($data['lat']))
       {
      $data['lat']="34.79441";
      $data['lng']="113.690895";
       }
        $page = request()->param("page", 1);
        $num = request()->param("page", 10);
         $start = ($page - 1) * $num;
       $where = [];
        $orwhere = [];
       if(!empty($data['quid'])){
            $where['province'] = $data['quid'];
           $orwhere['area'] = $data['quid'];
       }
       if(empty($data['name'])){
            $data['name'] = '';
        }
        $validate->check($data) || $this->error($validate->getError());
        $result = Db::name('store_shops')
        	->where($where)
        	->whereLike('shop_name','%'.$data['name'].'%')
            ->whereOr($orwhere)
            ->where(['is_disable' => 1])
            ->page($page, 20)
            ->select();
        if (empty($result)) $this->error('没有更多数据');
        foreach ($result as $k => $v) {
            $result[$k]['distance'] = round( $this->distance( $data['lat'],$data['lng'], $v['lat'], $v['lng']),2);
        }
        $this->success('', $result);
    }


    public
    function getShopsDetail()
    {
        $data = input('post.');
        $validate = Validate::make([
            'id' => 'require',
        ], [
            'id.require' => '缺少id！',
        ]);

        $id = input('id');
        if ($id == 0){
            $this->error('暂无服务商');
        }
//        $validate->check($data) || $this->error($validate->getError());
        $result = Db::name('store_shops')
            ->where(['is_disable' => 1, 'id' => $data['id']])
            ->find();
      
 		$data['lat']="34.79441";
        $data['lng']="113.690895";

        $result['distance'] = round( $this->distance( $data['lat'],$data['lng'], $result['lat'], $result['lng']),2);
//        dump($result['distance']);

        if (empty($result)) $this->error('厂家不存在或已经被下架');
        $contentUrl = 'http://' . $_SERVER['HTTP_HOST'] . '/index/index/shopsaddmember?shop_id=' . $data['id'] . '&time=' . time();
        $h5Url = "http://h5ip.cn/index/api?format=json&url=" . urlencode($contentUrl);
        $remote_url = json_decode(file_get_contents($h5Url), true);

        $remote_url['short_url'] = $contentUrl;
        $imgUrl = '/static/upload/' . md5($result['id'] . $result['phone']) . '.png';
        $file = ROOT_PATH . $imgUrl;
        makeQrcode($remote_url['short_url'], $file);
        $this->success('', ['qrcodeUrl' => 'http://' . $_SERVER['HTTP_HOST'] . $imgUrl, 'linkUrl' => $remote_url['short_url'], 'result' => $result]);
    }



    //获取区域位置
    public
     function getAreaList()
    {
        $areaList = Db::name('sys_address')->select();
        foreach ($areaList as $k => $v) {
            $areaList[$k]['name'] = $v['area_name'];
        }
        $cacheAreaList = \Cache::get('areaList');
        if (empty($cacheAreaList)) {
            \Smallsha\Classes\Tree::setConfig('id', 'area_parent_id', 'children');
            $result = \Smallsha\Classes\Tree::makeTree($areaList);
            \Cache::set('areaList', $result);
            $this->success($result);
        } else {
            $this->success($cacheAreaList);
        }

    }


    public
    function hot_update()
    {
        $this->success('', ['hot_update' => 0]);
    }

    public
    function getAppUpgradeConfig()
    {
        $res = [];
        $res['versionid'] = sysconf('versionid');
        $res['ios_app_download_link'] = sysconf('ios_app_download_link');
        $res['upgrade_content'] = sysconf('upgrade_content');
        $res['android_app_download_link'] = sysconf('android_app_download_link');
        $this->success($res);
    }
  
  
    public function  getsdk()
  {
        $this->success('', WechatService::webJsSDK('http://humei.fhtest.vip/system/#/union'));
  }

}

